package ljye.com.ljye.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import ljye.com.ljye.R;
import ljye.com.ljye.activity.Activity_ImageBrowse;
import ljye.com.ljye.adapter.Score_GridViewAdapter;
import ljye.com.ljye.layout.MyNineGridImageView;
import ljye.com.ljye.utils.CommonViewHolder;
import ljye.com.ljye.utils.Utils;
import ljye.com.ljye.view.MyGridView;


/**
 * 机构评论
 */
public class Fragment_Institution_home_evaluate extends Fragment {

    private View view;
    private ArrayList<String> listData;
    private ListView lv;
    private MyAdpapter adpapter;
    private TextView more;
    private List<String> urls_list;
    private MyGridView gridview;
    private ArrayList<String> listData1;

    private static final int ON_LOAD_MORE = 2;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ON_LOAD_MORE:
                    listData.add("加载数据");
                    adpapter.notifyDataSetChanged();
                    setListViewHeight(lv);
                    more.setText("更多评论");
                    break;
            }
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null == view) {
            view = inflater.inflate(R.layout.fragment_teacher_home_evaluate, container, false);
            lv = (ListView)view.findViewById(R.id.lv);
            more = (TextView)view.findViewById(R.id.more);
            gridview = (MyGridView)view.findViewById(R.id.gridview);
            initlistview();//评论条目
            initgridview();//评分条目
            urls_list = new ArrayList<>();
            urls_list.add("http://ww3.sinaimg.cn/large/610dc034jw1f5d36vpqyuj20zk0qo7fc.jpg");
            urls_list.add("http://ww3.sinaimg.cn/large/610dc034jw1f5byokn81tj20dw0hiwfe.jpg");
            urls_list.add("http://ww1.sinaimg.cn/large/7a8aed7bjw1f2sm0ns82hj20f00l8tb9.jpg");
            urls_list.add("http://ww3.sinaimg.cn/large/7a8aed7bjw1f2x7vxkj0uj20d10mi42r.jpg");

        }
        return view;
    }
    private void initgridview() {
        listData1 = new ArrayList<>();
        for (int i = 0; i <= 5; i++) {
            listData1.add("很不错的哦" + i);
        }
        Score_GridViewAdapter gridViewAdapter=new Score_GridViewAdapter(getActivity(),listData1);
        gridview.setAdapter(gridViewAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Utils.showToast(getActivity(),i+"");
            }
        });
    }
    private void initlistview() {
        listData = new ArrayList<>();
        for (int i = 0; i <= 5; i++) {
            listData.add("天才宝贝" + i);
        }
        adpapter = new MyAdpapter();
        lv.setAdapter(adpapter);
        setListViewHeight(lv);
        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                more.setText("正在加载数据...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        mHandler.sendEmptyMessage(ON_LOAD_MORE);
                    }
                }).start();
            }
        });
    }



    public class MyAdpapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listData == null ? 0 : listData.size();
        }

        @Override
        public Object getItem(int i) {
            return listData.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            CommonViewHolder holder = CommonViewHolder.createCVH(view, viewGroup, R.layout.item_home_evaluate);

            CircleImageView headPortrait = (CircleImageView) holder.getView(R.id.head_portrait);//头像
            TextView uesrId = (TextView) holder.getTv(R.id.uesr_id);//用户名
            RatingBar bar = holder.getView(R.id.rat, RatingBar.class);//评分星级 最高5级 可以半星
            TextView time = (TextView) holder.getTv(R.id.time);//日期时间
            TextView evaluate = (TextView) holder.getTv(R.id.evaluate);//评价内容

            TextView classTime = (TextView) holder.getTv(R.id.class_time);//课程时间
            MyNineGridImageView ngivNineGrid = (MyNineGridImageView) holder.getView(R.id.ngiv_nine_grid);//图片
            String s = listData.get(i);
            uesrId.setText(s);
            bar.setRating(3);//星级
            ngivNineGrid.setImgnumber(4);//设置一行显示多少张图片
            ngivNineGrid.setAdapter(mAdapter);
            ngivNineGrid.setImagesData(urls_list);

            return holder.convertView;

        }
    }
    private MyNineGridImageView.MyNineGridImageViewAdapter<String> mAdapter = new MyNineGridImageView.MyNineGridImageViewAdapter<String>() {
        @Override
        protected void onDisplayImage(Context context, final ImageView imageView, String url) {
            Transformation transformation = new Transformation() {

                @Override
                public Bitmap transform(Bitmap source) {

                    int targetWidth = imageView.getWidth();
//                    LogCat.i("source.getHeight()="+source.getHeight()+",source.getWidth()="+source.getWidth()+",targetWidth="+targetWidth);

                    if (source.getWidth() == 0) {
                        return source;
                    }

                    //如果图片小于设置的宽度，则返回原图
                    if (source.getWidth() < targetWidth) {
                        return source;
                    } else {
                        //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
                        double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                        int targetHeight = (int) (targetWidth * aspectRatio);
                        if (targetHeight != 0 && targetWidth != 0) {
                            Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                            if (result != source) {
                                // Same bitmap is returned if sizes are the same
                                source.recycle();
                            }
                            return result;
                        } else {
                            return source;
                        }
                    }

                }

                @Override
                public String key() {
                    return "transformation" + " desiredWidth";
                }

            };

            Picasso.with(context)
                    .load(url)
                    .placeholder(R.drawable.ic_default_image)
                    .transform(transformation)
                    .into(imageView);
        }

        @Override
        protected void onItemImageClick(Context context, int index, List list) {
            super.onItemImageClick(context, index, list);
//            Toast.makeText(context, "" + index, Toast.LENGTH_SHORT).show();
            ArrayList<String> imgs = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                imgs.add(list.get(i) + "");
//                Log.d("MainActivity", list.get(i) + "");
            }
            Intent intent = new Intent(getActivity(), Activity_ImageBrowse.class);
            intent.putExtra("position", index);
            intent.putStringArrayListExtra("imgs", imgs);
            startActivity(intent);
        }

    };
    //解决ScrollView包裹listview后只显示一个条目问题
    public void setListViewHeight(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

}
